package com.example.drss.adapter;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.example.drss.R;
import com.example.drss.itemdata.ItemData;


import android.R.integer;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class GridViewAdapter extends BaseAdapter {

	//可以将布局资源生成一个视图
		LayoutInflater inflater;
		//本例中是个avtivity对象
		Context context;
		
		List<ItemData> data;
		 public GridViewAdapter(Context context,List<ItemData> data) {
			 this.context=context;
			 this.data=data;
			 inflater=LayoutInflater.from(context);//加载显示的数据	
		}

		@Override
		public int getCount() {
			return data==null?0:data.size();		
		}

		@Override
		public Object getItem(int position) {
			return data==null?0:data.get(position);	
		}

		@Override
		public long getItemId(int position) {		
			return position;
		}
		
		private static class HolderView{
			public ImageView iconView;
			public TextView nameView;
		}
		private Bitmap loadBitmap(String filename){
			Resources resources=context.getResources();
			try {
				InputStream is=resources.getAssets().open(filename);
				Bitmap bitmap=BitmapFactory.decodeStream(is);
				return bitmap;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			HolderView holderView=null;
			if(convertView==null){
				holderView=new HolderView();
				convertView=inflater.inflate(R.layout.gridview_icon, parent, false);
				holderView.iconView=(ImageView)convertView.findViewById(R.id.imageView_image);
				holderView.nameView=(TextView)convertView.findViewById(R.id.textView_name);
				convertView.setTag(holderView);
			}
			else{
				holderView=(HolderView)convertView.getTag();
			}
			ItemData itemData=data.get(position);
			if(itemData.getImage()!=null){
				holderView.iconView.setImageBitmap(loadBitmap(itemData.getImage()+".jpg"));
			}

			holderView.nameView.setText(itemData.getName());
			return convertView;
		}
}
